import {
  User,
  LoginRequest,
  RegisterRequest,
  AuthResponse,
  Site,
  CreateSiteRequest,
  Certificate,
  CreateCertificateRequest,
  Container,
  CreateContainerRequest,
  DashboardStats,
  PaginatedResponse,
} from '../types';

const API_BASE_URL = process.env.REACT_APP_API_URL || 'http://192.168.40.54:8000';

class ApiService {
  private baseURL: string;

  constructor(baseURL: string = API_BASE_URL) {
    this.baseURL = baseURL;
  }

  private async request<T>(
    endpoint: string,
    options: RequestInit = {}
  ): Promise<T> {
    const url = `${this.baseURL}${endpoint}`;
    const token = localStorage.getItem('auth-token');

    const config: RequestInit = {
      headers: {
        'Content-Type': 'application/json',
        ...(token && { Authorization: `Bearer ${token}` }),
        ...options.headers,
      },
      ...options,
    };

    try {
      const response = await fetch(url, config);
      
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.detail || `HTTP ${response.status}: ${response.statusText}`);
      }

      return await response.json();
    } catch (error) {
      console.error('API request failed:', error);
      throw error;
    }
  }

  // 认证相关API
  async login(credentials: LoginRequest): Promise<AuthResponse> {
    return this.request<AuthResponse>('/auth/login', {
      method: 'POST',
      body: JSON.stringify(credentials),
    });
  }

  async register(userData: RegisterRequest): Promise<{ message: string; user: User }> {
    return this.request<{ message: string; user: User }>('/auth/register', {
      method: 'POST',
      body: JSON.stringify(userData),
    });
  }

  async getCurrentUser(): Promise<User> {
    return this.request<User>('/auth/me');
  }

  async refreshToken(): Promise<AuthResponse> {
    return this.request<AuthResponse>('/auth/refresh', {
      method: 'POST',
    });
  }

  async updateUserProfile(profileData: { email?: string; full_name?: string }): Promise<User> {
    return this.request<User>('/auth/profile', {
      method: 'PUT',
      body: JSON.stringify(profileData),
    });
  }

  // 站点管理API
  async getSites(): Promise<Site[]> {
    return this.request<Site[]>('/api/sites');
  }

  async getSite(id: number): Promise<Site> {
    return this.request<Site>(`/api/sites/${id}`);
  }

  async createSite(siteData: CreateSiteRequest): Promise<Site> {
    return this.request<Site>('/api/sites', {
      method: 'POST',
      body: JSON.stringify(siteData),
    });
  }

  async updateSite(id: number, siteData: Partial<CreateSiteRequest>): Promise<Site> {
    return this.request<Site>(`/api/sites/${id}`, {
      method: 'PUT',
      body: JSON.stringify(siteData),
    });
  }

  async deleteSite(id: number): Promise<{ message: string }> {
    return this.request<{ message: string }>(`/api/sites/${id}`, {
      method: 'DELETE',
    });
  }

  // 证书管理API
  async getCertificates(): Promise<Certificate[]> {
    return this.request<Certificate[]>('/api/certificates');
  }

  async getCertificate(id: number): Promise<Certificate> {
    return this.request<Certificate>(`/api/certificates/${id}`);
  }

  async createCertificate(certData: CreateCertificateRequest): Promise<Certificate> {
    return this.request<Certificate>('/api/certificates', {
      method: 'POST',
      body: JSON.stringify(certData),
    });
  }

  async updateCertificate(id: number, certData: Partial<CreateCertificateRequest>): Promise<Certificate> {
    return this.request<Certificate>(`/api/certificates/${id}`, {
      method: 'PUT',
      body: JSON.stringify(certData),
    });
  }

  async deleteCertificate(id: number): Promise<{ message: string }> {
    return this.request<{ message: string }>(`/api/certificates/${id}`, {
      method: 'DELETE',
    });
  }

  // 容器管理API
  async getContainers(): Promise<Container[]> {
    return this.request<Container[]>('/api/containers');
  }

  async getContainer(id: number): Promise<Container> {
    return this.request<Container>(`/api/containers/${id}`);
  }

  async createContainer(containerData: CreateContainerRequest): Promise<Container> {
    return this.request<Container>('/api/containers', {
      method: 'POST',
      body: JSON.stringify(containerData),
    });
  }

  async updateContainer(id: number, containerData: Partial<CreateContainerRequest>): Promise<Container> {
    return this.request<Container>(`/api/containers/${id}`, {
      method: 'PUT',
      body: JSON.stringify(containerData),
    });
  }

  async deleteContainer(id: number): Promise<{ message: string }> {
    return this.request<{ message: string }>(`/api/containers/${id}`, {
      method: 'DELETE',
    });
  }

  // 仪表板统计API
  async getDashboardStats(): Promise<DashboardStats> {
    return this.request<DashboardStats>('/api/dashboard/stats');
  }

  // 管理员API
  async getUsers(skip: number = 0, limit: number = 100): Promise<PaginatedResponse<User>> {
    return this.request<PaginatedResponse<User>>(`/admin/users?skip=${skip}&limit=${limit}`);
  }

  async createUser(userData: RegisterRequest & { is_superuser?: boolean }): Promise<User> {
    return this.request<User>('/admin/users', {
      method: 'POST',
      body: JSON.stringify(userData),
    });
  }

  async updateUser(id: number, userData: Partial<RegisterRequest & { is_superuser?: boolean }>): Promise<User> {
    return this.request<User>(`/admin/users/${id}`, {
      method: 'PUT',
      body: JSON.stringify(userData),
    });
  }

  async deleteUser(id: number): Promise<{ message: string }> {
    return this.request<{ message: string }>(`/admin/users/${id}`, {
      method: 'DELETE',
    });
  }

  async getAdminStats(): Promise<any> {
    return this.request<any>('/admin/stats');
  }

  // AKSK配置管理API
  async getAKSKConfigs(): Promise<any[]> {
    return this.request<any[]>('/api/aksk');
  }

  async createAKSKConfig(configData: any): Promise<any> {
    return this.request<any>('/api/aksk', {
      method: 'POST',
      body: JSON.stringify(configData),
    });
  }

  async updateAKSKConfig(id: number, configData: any): Promise<any> {
    return this.request<any>(`/api/aksk/${id}`, {
      method: 'PUT',
      body: JSON.stringify(configData),
    });
  }

  async deleteAKSKConfig(id: number): Promise<{ message: string }> {
    return this.request<{ message: string }>(`/api/aksk/${id}`, {
      method: 'DELETE',
    });
  }

  async setDefaultAKSKConfig(id: number): Promise<{ message: string }> {
    return this.request<{ message: string }>(`/api/aksk/${id}/set-default`, {
      method: 'POST',
    });
  }
}

export const apiService = new ApiService();
export default apiService; 